import React,{Component} from 'react'
import PropTypes from 'prop-types'

class ClickCounter extends Component{

    constructor(props){
        super(props);
        this.onClickButton = this.onClickButton.bind(this);
        this.state = {
            count:this.props.initValue,
            buttonText:this.props.buttonText};

            console.log("ClickCounter -> constructor");

    }

    componentWillMount(){

        console.log("ClickCounter -> componentWillMount");
    }

    componentDidMount(){

        console.log("ClickCounter -> componentDidMount");
    }

    shouldComponentUpdate(nextProps,nextStates){
        console.log("shouldComponentUpdate");
        var propsNotChange = this.props.initValue === nextProps.initValue && this.props.buttonText == nextProps.buttonText;
        var stateNotChange = this.state.count == nextStates.count;

        console.log("old count :%d next count: %d",this.state.count,nextStates.count);

        if(propsNotChange && stateNotChange){
            console.log("shouldComponentUpdate 参数一致，不必重新渲染");
            return true;
        }
        console.log("shouldComponentUpdate 参数不一致，重新渲染");
        return true;
    }


    onClickButton(){
        var current = this.state.count;
        var next = current + 1;
        this.setState({count: next});
        this.props.onUpdate(current,next);
        console.log("onClickButton");
    }
    render(){
        console.log("ClickCounter -> render");
        const style = {
            margin: '20px'
        };
        return(
            <div style={style}>
                <button onClick={this.onClickButton}>{this.state.buttonText}</button>&nbsp;&nbsp;
                <span>Click Count:{this.state.count}</span>
            </div>
        );
    }
}

ClickCounter.defaultProps={
    initValue:28,
    buttonText:"DefaultText",
    onUpdate: f=>f
}

ClickCounter.propTypes={
    initValue:PropTypes.number,
    buttonText:PropTypes.string.isRequired,
    onUpdate:PropTypes.func
}

export default ClickCounter;